import React,{useEffect,useCallback} from 'react';
import {Form, Input, Select, DatePicker, Button, Space, Modal} from "antd";

interface dataType {
    username:string;
    phoneNum:string;
    email:string;
}
interface propsType {
    modalShow:boolean;
    title:string;
    data:dataType;
    modalOk(data: object): void;
    modalCancel(data: object): void;
}
function EditForm(props) {
    const {modalShow,title,data,modalCancel,modalOk} = props
    const {username,phoneNum,email} = data
    const [editForm] = Form.useForm();
    useEffect(()=>{
        editForm.setFieldsValue({...data});
    },[data,editForm,modalShow])
    const modalSubmit = () => {
        editForm.validateFields().then((values) => {
            modalOk(values)
        })
    }
    const cancel = () => {
        modalCancel()
        setTimeout(()=>{
            editForm.resetFields()
        },800)
    }
    const verifyEmail = (value,callback) => {
       let regex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if(value && !regex.test(value)){
            callback(new Error('邮箱格式不正确！'))
        }else{
            callback()
        }
    }
    const verifyPhone = (value,callback) => {
        let regex = /^1[3-9]\d{9}$/
        if(value && !regex.test(value)){
            callback(new Error('手机号格式不正确！'))
        }else{
            callback()
        }
    }
    return (
        <Modal
            open={modalShow}
            title={title}
            onOk={modalSubmit}
            onCancel={cancel}
            footer={(_, { OkBtn, CancelBtn }) => (
                <>
                    <CancelBtn />
                    <OkBtn />
                </>
            )}
        >
            <Form
                form={editForm}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 14 }}
                layout="horizontal"
            >
                <Form.Item label="用户名：" name="username" rules={[{ required: true,message:'请输入用户名'}]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="手机号：" name="phoneNum" rules={[
                    {
                        validator:(_,value,callback)=>{
                            return verifyPhone(value,callback)
                        }
                    },
                ]}>
                    <Input/>
                </Form.Item>
                <Form.Item label="邮箱：" name="email" rules={[
                    { required: true,message:'请输入邮箱'},
                    {
                        validator:(_,value,callback)=>{
                            return verifyEmail(value,callback)
                        }
                    },
                ]}>
                    <Input/>
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default EditForm;
